package second.linkedlist;

public class Solution03 {
}


class MyLinkedList {
    int size;
    ListNode head;

    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }

    public int get(int index) {
        if (index >= size || index < 0) {
            return -1;
        }
        ListNode p = head;
        while (index-- > 0) {
            p = p.next;
        }
        return p.next.val;
    }

    public void addAtHead(int val) {
        ListNode tmp = new ListNode(val);
        tmp.next = head.next;
        head.next = tmp;
        size++;
    }

    public void addAtTail(int val) {
        ListNode tmp = new ListNode(val);
        ListNode p = head;
        while (p.next != null) {
            p = p.next;
        }
        p.next = tmp;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if (index > size || index < 0) return;
        ListNode tmp = new ListNode(val);
        ListNode p = head;
        while (index-- > 0) {
            p = p.next;
        }
        tmp.next = p.next;
        p.next = tmp;
        size++;
    }

    public void deleteAtIndex(int index) {
        if (index >= size || index < 0) return;
        ListNode p = head;
        while (index-- > 0) {
            p = p.next;
        }
        p.next = p.next.next;
        size--;
    }
}